<template>
  <a-layout>
    <a-layout-header class="bg-white admin-content-header">
      <div class="col-4 admin-tiao-left">
        <span>{{ $route.name }}</span>
      </div>
      <div class="col-8 text-right">
        <el-button-group>
          <el-button type="primary" @click="adduser" icon="el-icon-edit" v-text="`添加用户`"></el-button>
          <el-button type="primary" @click="selectAllcourse" v-text="'批量添加课程'"></el-button>
          <router-link :to="{'name': '添加学生'}">
            <el-button type="primary" icon="el-icon-edit">添加学生</el-button>
          </router-link>
          <a
            href="https://hte-public.oss-cn-qingdao.aliyuncs.com/hterobot_student_list.xlsx"
            target="view_window"
          >
            <el-button type="primary" icon="el-icon-edit">下载学生模板</el-button>
          </a>
        </el-button-group>
      </div>
      <el-drawer :title="`${title}用户`" :visible.sync="dialogVisiblet">
        <el-form :rules="rules" ref="ruleForm" :model="formdate">
          <el-form-item label="用户名称" :label-width="formLabelWidth">
            <el-input v-model="formdate.username" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" :label-width="formLabelWidth">
            <el-input v-model="formdate.password" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户手机" :label-width="formLabelWidth">
            <el-input v-model="formdate.phonenum" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" :label-width="formLabelWidth">
            <el-input v-model="formdate.useremail" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="用户类型" :label-width="formLabelWidth">
            <el-select v-model="formdate.usertype" auto-complete="off">
              <el-option
                v-for="item in usertypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户地址" :label-width="formLabelWidth">
            <el-cascader
              :options="address()"
              :props="{value:'label'}"
              v-model="selectedOptions"
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="线下用户" :label-width="formLabelWidth">
            <el-radio v-model="formdate.isnetwork" :label="true">线上用户</el-radio>
            <el-radio v-model="formdate.isnetwork" :label="false">线下用户</el-radio>
          </el-form-item>
          <el-form-item label :label-width="formLabelWidth">
            <el-button @click="dialogVisiblet = false">取 消</el-button>
            <el-button type="primary" @click="onSubmit('ruleForm')">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
      <el-dialog title="提示" :visible.sync="dialogVisibled" width="800px">
        <changemodel
          v-bind="{ allData:getCourse, selectDate:[], clickdata, group: getCatebag , groupdata }"
        ></changemodel>
      </el-dialog>
    </a-layout-header>
    <a-layout-content class="admin-content-table">
      <el-table
        height="100%"
        class="text-center"
        :data="tableDate"
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column fixed type="selection" width="55"></el-table-column>
        <el-table-column fixed prop="userid" sortable label="用户ID" width="150"></el-table-column>
        <el-table-column prop="username" label="姓名" width="120"></el-table-column>
        <el-table-column prop="usertype" sortable label="用户类型" width="120"></el-table-column>
        <el-table-column prop="phonenum" sortable label="手机号码" width="120"></el-table-column>
        <el-table-column prop="address" label="地区">
          <template slot-scope="scope">
            <span v-text="Object.values(scope.row.address?scope.row.address:{})"></span>
          </template>
        </el-table-column>
        <el-table-column prop="createtime" sortable label="最近登陆" width="210">
          <template slot-scope="scope">
            <span v-text="new Date(scope.row.lastlogintime).toLocaleString()"></span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="120">
          <template slot-scope="scope">
            <el-button
              v-for="v in scope.row.remarks"
              :key="v.ID"
              type="text"
              @click="remarks(scope.row, v)"
            >{{v.content}}</el-button>
            <el-button type="text" v-show="!scope.row.remarks.length" @click="remarks(scope.row)">备注</el-button>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="280" show-overflow-tooltip>
          <template slot="header">
            <input class="el-input__inner" v-model.lazy="search" placeholder="请输入内容" />
          </template>
          <template slot-scope="scope">
            <el-button class="position-relative">
              <router-link
                :to="{ name:'查看用户', params: { userid: scope.row.userid } }"
                class="stretched-link"
              >查看</router-link>
            </el-button>
            <el-button type="info" @click="adduser(scope.row)">修改</el-button>
            <el-button type="danger" @click="deldata({uid:scope.row.userid})" icon="el-icon-delete"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </a-layout-content>
    <adminContentFooter
      v-bind="{handleSizeChange, handleCurrentChange, currentPage, pagesize,data}"
    ></adminContentFooter>
  </a-layout>
</template>

<script>
import {
  asyncdeleteUserByID,
  asyncnewAgent,
  asyncupdateUser,
  asyncaddUsercouser,
  asynccreateremaproposal
} from "../../../plugins/api.js";
import { mapGetters } from "vuex";
import adminContentFooter from "@/components/admin/admin-content-footer.vue";
import changemodel from "../../../components/admin/changemodel";
const address = window.address || [];
export default {
  data() {
    return {
      title: "添加",
      idnum: [],
      sels: [],
      formLabelWidth: "140px",
      dialogVisiblet: false, // 添加修改用户
      dialogVisibled: false, // 添加课程
      dialogVisibletm: false, // 添加备注
      adcourse: false,
      prop: "",
      myusername: "",
      selectedOptions: [],
      usertypes: [
        {
          value: "Tourist",
          label: "游客"
        },
        {
          value: "User",
          label: "用户"
        },
        {
          value: "Agent",
          label: "代理商"
        },
        {
          value: "Admin",
          label: "管理员"
        },
        {
          value: "Teacher",
          label: "教师"
        },
        {
          value: "Student",
          label: "学生"
        }
      ],
      currentPage: 1,
      pagesize: 20,
      search: "",
      options: this.$store.state.options,
      formdate: {},
      rules: {}
    };
  },
  computed: {
    ...mapGetters([
      "getCourse",
      "getUser",
      "getCatebag",
      "getCoursecatebag",
      "getuser"
    ]),
    groupdata() {
      return this.getCoursecatebag.map(({ ID, cid, catebagid }) => {
        return { ID, groupid: catebagid, childid: cid };
      });
    },
    tableDate() {
      const { currentPage, pagesize, data } = this;
      return data.slice((currentPage - 1) * pagesize, currentPage * pagesize);
    },
    data() {
      const { getUser, search } = this;
      return getUser.filter(data => {
        const arr = JSON.stringify(Object.values(data));
        return !search || arr.toLowerCase().includes(search.toLowerCase());
      });
    }
  },
  methods: {
    address() {
      return address;
    },
    selectAllcourse() {
      const { sels } = this;
      if (sels.length) {
        this.dialogVisibled = true;
      } else {
        this.$message("请选择用户");
      }
    },
    async remarks({ userid }, data) {
      const { getuser } = this;
      this.$prompt("请输入备注", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then(async ({ value }) => {
          if (!value) return;
          if (data) {
            const { ID } = data;
            await asynccreateremaproposal({
              ID,
              uid: getuser.userid,
              username: getuser.username,
              content: value,
              userID: userid
            });
          } else {
            await asynccreateremaproposal({
              uid: getuser.userid,
              username: getuser.username,
              content: value,
              userID: userid
            });
          }
          this.$message({
            type: "success",
            message: "添加成功"
          });
          this.$store.dispatch("actionUser");
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    handleSizeChange(val) {
      this.pagesize = val;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
    handleSelectionChange(val) {
      this.sels = val;
    },
    handleChange() {
      const data = {
        province: this.selectedOptions[0],
        city: this.selectedOptions[1],
        area: this.selectedOptions[2]
      };
      this.formdate.address = data;
      console.log(123);
    },
    adduser(data) {
      if (data) {
        this.formdate = JSON.parse(JSON.stringify(data));
        this.title = "修改";
      } else {
        this.formdate = {
          password: "",
          usertype: "User",
          username: "",
          useremail: "",
          phonenum: "",
          area: "0086",
          address: {},
          isnetwork: false
        };
        this.title = "添加";
      }
      this.dialogVisiblet = true;
    },
    async onSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            const { formdate, title } = this;
            if (formdate.userid) {
              await asyncupdateUser(formdate);
            } else {
              await asyncnewAgent(formdate);
            }
            this.$store.dispatch("actionUser");
            this.$message({
              message: `恭喜你，${title}成功`,
              type: "success"
            });
            this.dialogVisiblet = false;
          } catch (err) {
            this.$message.error(err);
          }
        } else {
          return false;
        }
      });
    },
    async deldata(i) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          try {
            await asyncdeleteUserByID(i);
            this.$store.dispatch("actionUser");
            this.$message({
              message: "恭喜你，删除成功",
              type: "success"
            });
          } catch (err) {
            this.$message.error("错了哦，删除失败:" + err);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async clickdata({ ID }) {
      const { sels } = this;
      this.$notify({
        title: "提示",
        message: "添加中"
      });

      for (let v of sels) {
        try {
          await asyncaddUsercouser({ uid: v.userid, cid: ID });
        } catch (err) {
          console.log(err);
        }
      }
      this.$notify({
        title: "成功",
        message: "添加成功",
        type: "success"
      });
    }
  },
  components: {
    adminContentFooter,
    changemodel
  }
};
</script>
<style scope>
</style>
